package loveqq.crud.controller;

import loveqq.crud.entity.User;
import loveqq.crud.query.UserQuery;
import loveqq.crud.service.UserService;
import loveqq.crud.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Controller
public class UserController {

    @Autowired
    UserService userService;

    @Bean
    public RouterFunction<ServerResponse> userRouter() {
        return RouterFunctions.route()
                .path("/user", builder -> builder
                        .GET("/findAll", this::findAll)
                        .GET("/search", this::search)
                        .POST("/save", this::save)
                        .DELETE("/remove/{id}", this::remove)
                        .PUT("/update", this::update)
                ).build();
    }

    public Mono<ServerResponse> findAll(ServerRequest request) {
        // return userService.findAll()
        //         .as(WebUtil::response);
        return WebUtil.response(
                userService.findAll()
        );
    }

    public Mono<ServerResponse> search(ServerRequest request) {
        // return request.bodyToMono(UserQuery.class)
        //         .as(userService::search)
        //         .as(WebUtil::response);
        return WebUtil.response(
                request.bodyToMono(UserQuery.class).as(userService::search)
        );
    }

    public Mono<ServerResponse> save(ServerRequest request) {
        // return request.bodyToMono(User.class)
        //         .as(userService::save)
        //         .as(WebUtil::response);
        return WebUtil.response(
                request.bodyToMono(User.class).as(userService::save)
        );
    }

    public Mono<ServerResponse> remove(ServerRequest request) {
        // String ids = request.pathVariable("id");
        // return Flux.just(ids.split(","))
        //         .map(Long::valueOf)
        //         .as(userService::remove)
        //         .as(WebUtil::response);
        return WebUtil.response(() -> {
            String ids = request.pathVariable("id");
            return Flux.just(ids.split(","))
                    .map(Long::valueOf)
                    .as(userService::remove);
        });
    }

    public Mono<ServerResponse> update(ServerRequest request) {
        // return request.bodyToMono(User.class)
        //         .as(userService::update)
        //         .as(WebUtil::response);
        return WebUtil.response(
                request.bodyToMono(User.class).as(userService::update)
        );
    }

}
